package com.xiaoxiao.springbootstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxiao.springbootstudy.pojo.RoleMenu;
import com.xiaoxiao.springbootstudy.pojo.Roler;
import com.xiaoxiao.springbootstudy.service.RoleMenuService;
import com.xiaoxiao.springbootstudy.service.RolerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.management.relation.Role;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class RoleController {
    @Autowired
    RolerService rolerService;
    @Autowired
    private RoleMenuService roleMenuService;

    @GetMapping("/listRolers")
    public Map<String, Object> listRolers(@RequestParam(defaultValue = "1" ) Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        return rolerService.queryRolePageService(pageNum, pageSize);
    }

    @GetMapping("/allRoles")
    public List<Roler> getAllRoles() {
        QueryWrapper<Roler> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name");
        return rolerService.list(queryWrapper);
    }

    @PostMapping("/updateRoler")
    public Map<String, Object> updateRoler(@RequestBody Roler role) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "更新角色失败");

        try {
            rolerService.updateById(role);

            result.put("code", 200);
            result.put("msg", "更新角色成功");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @PostMapping("/addRoler")
    public Map<String, Object> addRoler(@RequestBody Roler roler) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "添加角色失败");

        try {
            rolerService.save(roler);

            result.put("code", 200);
            result.put("msg", "添加角色成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @GetMapping("/deleteRoler/{id}")
    public Map<String, Object> deleteRoler(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("msg", "删除角色失败");

        try {
            rolerService.removeById(id);

            //删除角色对应的菜单信息
            QueryWrapper<RoleMenu> cond=new QueryWrapper<>();
            cond.eq("rid",id);
            roleMenuService.remove(cond);

            result.put("code", 200);
            result.put("msg", "删除角色成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
